<script setup lang="ts">
import type { VxeGridProps } from '@vben/plugins/src/vxe-table/types';

import type { RowType } from './qrtzJobLog.data';

import { createVNode, nextTick, ref } from 'vue';

import { AccessControl } from '@vben/access';
import { useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { AntDesignOutLined } from '@vben/icons';

import { message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  qrtzJobLogDelApi,
  qrtzJobLogDeleteBatchApi,
  qrtzJobLogQueryByIdApi,
  qrtzJobLogQueryPageListApi,
} from '#/api/quartz/qrtzJobLog';
import { SparkDescriptions } from '#/components';
import { useDictionaries } from '#/utils';

import QrtzJobLogFormModal from './modules/QrtzJobLogFormModal.vue';
import { DetailsColumns } from './qrtzJobLog.data.ts';

const { translateValue } = useDictionaries(['ok_fail']);

const detailsRef = ref();
const record = ref({});

const [Drawer, drawerApi] = useVbenDrawer({
  title: '执行日志',
  showConfirmButton: false,
  cancelText: '关闭',
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      record.value = drawerApi.getData<Record<string, any>>();
      initFun({ jobId: record.value.id });
    }
  },
});

const gridOptions: VxeGridProps<RowType> = {
  height: 'auto',
  toolbarConfig: {
    slots: {
      buttons: 'toolbar-buttons',
    },
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left', align: 'center' },
    { title: '序号', type: 'seq', width: 50, fixed: 'left', align: 'center' },
    {
      title: '任务名称',
      field: 'jobId_dictText',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '调用目标字符串',
      field: 'invokeTarget',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '日志信息',
      field: 'jobMessage',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '执行状态',
      field: 'status',
      align: 'center',
      minWidth: 100,
      cellRender: {
        name: 'CellDict',
        attrs: {
          dictCode: 'ok_fail',
          translateValue,
        },
      },
    },
    {
      title: '异常信息',
      field: 'exceptionInfo',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '主键',
      field: 'id',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '创建人',
      field: 'createBy',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '创建时间',
      field: 'createTime',
      align: 'center',
      minWidth: 100,
    },
    {
      title: '更新人',
      field: 'updateBy',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '更新时间',
      field: 'updateTime',
      align: 'center',
      minWidth: 100,
      visible: false,
    },
    {
      title: '操作',
      field: 'action',
      align: 'center',
      minWidth: 160,
      fixed: 'right',
      slots: {
        default: 'action',
      },
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        return await qrtzJobLogQueryPageListApi({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
const [FromModal] = useVbenModal({
  connectedComponent: QrtzJobLogFormModal,
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      gridApi.query();
    }
  },
});
// async function handlerAdd() {
//   formModalApi.setData({ id: undefined });
//   formModalApi.open();
// }
// async function handlerEdit(row) {
//   formModalApi.setData({ id: row.id });
//   formModalApi.open();
// }

async function initFun(params) {
  message.info('数据加载中...');
  // 等待 DOM 更新
  await nextTick();
  try {
    await gridApi.query(params);
  } catch {
    message.error('数据加载失败!');
  }
}
async function handlerDel(row) {
  const msg = await qrtzJobLogDelApi(row.id);
  message.success(msg);
  await gridApi.query();
}
async function handlerBatchDel() {
  const checkboxRecords = gridApi.grid.getCheckboxRecords();
  if (checkboxRecords.length === 0) {
    message.warn('至少选中一行');
  } else {
    const idArray = checkboxRecords.map((record) => record.id);
    const ids = idArray.join(',');
    Modal.confirm({
      title: '系统提示?',
      content: createVNode(
        'div',
        { style: 'color:red;' },
        '确认删除所选中行吗?',
      ),
      onOk() {
        qrtzJobLogDeleteBatchApi(ids).then(() => {
          message.success('删除成功');
          gridApi.query();
        });
      },
      class: 'test',
    });
  }
}
async function handlerDetails(row) {
  detailsRef.value.open({ id: row.id }, DetailsColumns);
}
</script>

<template>
  <Drawer>
    <FromModal class="w-[50%]" />
    <SparkDescriptions
      class="w-[60%]"
      title="定时任务日志详情"
      ref="detailsRef"
      :api="qrtzJobLogQueryByIdApi"
    />
    <Grid>
      <template #toolbar-buttons>
        <!--                <a-button-->
        <!--                  v-access:code="'quartz:qrtzJobLog:add'"-->
        <!--                  type="primary"-->
        <!--                  class="mr-2"-->
        <!--                  @click="handlerAdd()"-->
        <!--                >-->
        <!--                  新增-->
        <!--                </a-button>-->
      </template>
      <template #toolbar-tools>
        <a-button
          v-access:code="'quartz:qrtzJobLog:batchDel'"
          type="primary"
          danger
          @click="handlerBatchDel()"
        >
          批量删除
        </a-button>
      </template>
      <template #action="{ row }">
        <!--        <a-button-->
        <!--          v-access:code="'quartz:qrtzJobLog:edit'"-->
        <!--          type="link"-->
        <!--          size="small"-->
        <!--          @click="handlerEdit(row)"-->
        <!--        >-->
        <!--          编辑-->
        <!--        </a-button>-->
        <a-popconfirm
          cancel-text="再想想"
          title="您确定要删除吗?"
          @confirm="handlerDel(row)"
        >
          <a-button
            v-access:code="'quartz:qrtzJobLog:del'"
            type="link"
            danger
            size="small"
          >
            删除
          </a-button>
        </a-popconfirm>
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <AccessControl :codes="['quartz:qrtzJobLog:details']" type="code">
                <a-menu-item key="1" @click="handlerDetails(row)">
                  详情
                </a-menu-item>
              </AccessControl>
            </a-menu>
          </template>
          <a-button
            v-access:code="'quartz:qrtzJobLog:more'"
            size="small"
            type="link"
            @click.prevent
          >
            更多
            <AntDesignOutLined />
          </a-button>
        </a-dropdown>
      </template>
    </Grid>
  </Drawer>
</template>
